package 多线程初阶.示例测试;

import java.util.Random;
/**
 * 实现一个阻塞队列
 * 通过 "循环队列" 的方式来实现
 * 使用 synchronized 进行加锁控制
 * put 插入元素的时候, 判定如果队列满了, 就进行 wait. (注意, 要在循环中进行 wait. 被唤醒时不一定队列就不满了, 因为同时可能是唤醒了多个线程).
 * take 取出元素的时候, 判定如果队列为空, 就进行 wait. (也是循环 wait)
 */
class MyBlockingQueue{
    private int[] items = new int[1000];//阻塞队列
    private int head = 0;  // 队首的位置
    private int tail = 0;// 队尾的位置
    volatile private int size = 0;// 队列的元素个数
    public void put(int value) throws InterruptedException {
        synchronized (this){
            while(size== items.length){
                this.wait();
            }
            items[tail]=value;
            tail++;
            if(tail== items.length){
                tail=0;
            }
            size++;
            this.notify();
        }
    }
    public int take() throws InterruptedException {
        int value=0;
        synchronized (this){
            while (size==0){
                this.wait();
            }
            value=items[head];
            head++;
            if (head==items.length){
                head=0;
            }
            size--;
            this.notify();
        }
        return value;
    }
}
public class TestDemo20 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue blockingQueue=new MyBlockingQueue();
        Thread customer=new Thread(()->{
            while (true){
                try {
                    int value=blockingQueue.take();
                    Thread.sleep(1000);
                    System.out.println("消费元素:"+value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者");
        customer.start();
        Thread producer=new Thread(()->{
            Random random=new Random();
            while (true){
                int value=random.nextInt(1000);
                try {
                    blockingQueue.put(value);
                    System.out.println("生产元素:"+value);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();
        customer.join();
        producer.join();
    }
}
